//
//  BCSImage.swift
//  BCFoundation
//
//  Created by Basic on 2021/1/6.
//  swift Image 扩展

import UIKit


public extension UIImage {
    
    /// 初始化图片
    /// - Parameter rgb: 颜色rgb
    convenience init?(rgb: UInt) {
        let color = UIColor(rgb: rgb)
        self.init(color:color)
    }
    
    /// 初始化图片
    /// - Parameters:
    ///   - color: 颜色
    ///   - size: 默认{1,1}
    convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
      let rect = CGRect(origin: .zero, size: size)
      UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
      color.setFill()
      UIRectFill(rect)
      let image = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      
      guard let cgImage = image?.cgImage else { return nil }
      self.init(cgImage: cgImage)
    }
    /// 从 Frmamework 里的 bundle 中加载图片，优先读取 main bundle 同名图片
    /// - Parameters:
    ///   - name: 需要加载的图片
    ///   - frameworkCls: framework 里的任意 class，用来获取 framework 路径
    ///   - bundleName: 图片所在的 bundle 名称，不带 .bundle 扩展名
    /// - Returns: 返回图片
    static func bc_imageWithFramework(_ name:String, _ frameworkCls:AnyObject?, _ bundleName:String?) -> UIImage? {
        if let image = UIImage(named: name) {
            return image
        }
        guard let _frameworkCls = frameworkCls else {
            return nil
        }
        var imgPath:String = Bundle(for: type(of: _frameworkCls)).resourcePath ?? ""
        if let bundleName_ = bundleName {
            imgPath = imgPath.appendingFormat("/%@.bundle/%@", bundleName_, name)
        }
        else {
            imgPath = imgPath.appendingFormat("/%@", name)
        }
        return UIImage(contentsOfFile: imgPath)
    }
}
